<script setup lang="ts" name="InstitutionalData">
import {ref, reactive, onActivated} from 'vue'
import {FormRules, ElMessage} from 'element-plus'
import {FromItem} from '@/components/dFrom/dFrom'
import dFrom from '@/components/dFrom/dFrom.vue'
import {Number, NoChineseEmty, Normal, PhoneLandline, transfDicArrData, NumberDot} from '@/util/common'
import {getHierarchicList, getInstitutionalData, InstitutionalData, saveInstitutionalData} from '@/api/baseSetting/institutionalData'
import userCommon from '@/store/common'
import useUser from '@/store/user'
import {SeleteData} from '@/api/config'
const common = userCommon.setup().store

const user = useUser.setup().store

const loading = ref(false)

const orgLevelData = ref<Array<SeleteData>>([])

const rules = reactive<FormRules>({
  orgCode: [
    {required: true, message: '请输入机构编码', trigger: ['change', 'blur']},
    {
      message: '最多3位数字',
      trigger: ['change', 'blur'],
      max: 3
    },
    {
      message: '请输入数字',
      pattern: Number,
      trigger: ['change', 'blur']
    }
  ],
  gwOrgCode: [
    {
      message: '最多20个字符',
      trigger: ['change', 'blur'],
      max: 20
    },
    {
      message: '请输入字母、数字、字符',
      pattern: NoChineseEmty,
      trigger: ['change', 'blur']
    }
  ],
  orgName: [
    {
      required: true,
      message: '请输入体检机构名称',
      trigger: ['change', 'blur']
    },
    {
      message: '最多50个字符',
      trigger: ['change', 'blur'],
      max: 50
    },
    {
      message: '请输入汉字、字母、数字、字符',
      pattern: Normal,
      trigger: ['change', 'blur']
    }
  ],
  telephone: [
    {
      required: true,
      message: '请输入机构电话',
      trigger: ['change', 'blur']
    },
    {
      message: '最多50个字符',
      trigger: ['change', 'blur'],
      max: 50
    },
    {
      message: '请输入汉字、字母、数字、字符',
      pattern: Normal,
      trigger: ['change', 'blur']
    }
  ],
  linkman: [
    {
      required: true,
      message: '请输入联系人',
      trigger: ['change', 'blur']
    },
    {
      message: '最多20个字符',
      trigger: ['change', 'blur'],
      max: 20
    },
    {
      message: '请输入汉字、字母、数字、字符',
      pattern: Normal,
      trigger: ['change', 'blur']
    }
  ],
  grade: [{required: true, message: '请选择机构等级', trigger: ['change', 'blur']}],
  phone: [
    {
      message: '最多11个字符',
      trigger: ['change', 'blur'],
      max: 11
    },
    {
      message: '请输入正确的电话号码',
      pattern: PhoneLandline,
      trigger: ['change', 'blur']
    }
  ],
  innerIp: [
    {
      required: true,
      message: '请输入内网环境IP',
      trigger: ['change', 'blur']
    },
    {
      message: '最多20个字符',
      trigger: ['change', 'blur'],
      max: 20
    },
    {
      message: '请输入数字、字符(.)',
      pattern: NumberDot,
      trigger: ['change', 'blur']
    }
  ],
  address: [
    {
      message: '最多100个字符',
      trigger: ['change', 'blur'],
      max: 100
    },
    {
      message: '请输入汉字、字母、数字、字符',
      pattern: Normal,
      trigger: ['change', 'blur']
    }
  ]
})
//表单数据
const formData = reactive<InstitutionalData>({
  orgCode: '',
  gwOrgCode: '',
  orgName: '',
  phone: '',
  linkman: '',
  grade: '',
  districtArr: [],
  telephone: '',
  districtCode: '',
  parentCode: '',
  provinceCode: '',
  address: '',
  innerIp: ''
})

//表单项
const fromItems = reactive<Array<FromItem>>([
  {
    label: '机构编码',
    prop: 'orgCode',
    type: 'input',
    placeholder: '请输入机构编码',
    disabled: !!formData.orgCode
  },
  {
    label: '单位编码',
    prop: 'gwOrgCode',
    type: 'input',
    placeholder: '请输入单位编码',
    disabled: !!formData.gwOrgCode
  },
  {
    label: '体检机构名称',
    prop: 'orgName',
    type: 'input',
    placeholder: '请输入体检机构名称'
  },
  {
    label: '机构等级',
    prop: 'grade',
    type: 'selete',
    placeholder: '请选择机构等级',
    seleteData: orgLevelData.value
  },
  {label: '机构电话', prop: 'telephone', type: 'input', placeholder: '请输入机构电话'},
  {label: '联系人', prop: 'linkman', type: 'input', placeholder: '请输入联系人'},
  {label: '联系电话', prop: 'phone', type: 'input', placeholder: '请输入联系电话'},
  {label: '内网环境IP', prop: 'innerIp', type: 'input', placeholder: '请输入内网环境IP'},
  {
    label: '机构地址',
    prop: 'districtArr',
    placeholder: '请选择省/市/区',
    type: 'slot',
    slotName: 'districtArr'
  },
  {
    label: '',
    placeholder: '请输入详细地址',
    prop: 'address',
    type: 'input',
    inputType: 'textarea'
  }
])

const cascaderProps = {
  checkStrictly: true,
  lazy: true,
  lazyLoad(node, resolve) {
    const {level, data} = node
    getHierarchicList({parentCode: data.value}).then((res) => {
      const arr: Array<{value: string; label: string; leaf: boolean}> = []
      if (res.data.data && res.data.data.length) {
        res.data.data.forEach((a) => {
          arr.push({
            value: a.districtCode,
            label: a.districtName,
            leaf: level >= 2
          })
        })
      } else {
        arr.push({label: '暂无', value: '', leaf: true})
      }
      resolve(arr)
    })
  }
}

const InitInstitutionalData = () => {
  getInstitutionalData().then((res) => {
    const {data} = res.data
    Object.assign(formData, res.data.data)
    user.refreshUserOrgInfo(data) // 更新store数据
    // 判断行政区域编码
    if (formData.districtCode === formData.provinceCode) {
      formData.districtArr = [formData.districtCode]
    } else {
      if (formData.provinceCode === formData.parentCode) {
        formData.districtArr = [formData.provinceCode, formData.districtCode]
      } else {
        formData.districtArr = [formData.provinceCode, formData.parentCode, formData.districtCode]
      }
    }
    fromItems.forEach((item) => {
      item.prop === 'orgCode' && (item.disabled = !!formData.orgCode)
      item.prop === 'gwOrgCode' && (item.disabled = !!formData.gwOrgCode)
    })
  })
}

//表单清除控制
const resetFieldsFlag = ref(false)
const validateFlag = ref(false)

//表单验证通过事件
const onSubmit = () => {
  const {id, orgCode, gwOrgCode, orgName, telephone, linkman, grade, address, innerIp} = formData
  const params: Partial<InstitutionalData> = {
    id,
    orgCode,
    gwOrgCode,
    orgName,
    telephone,
    linkman,
    grade,
    address,
    innerIp
  }
  params.phone = formData.phone || ''
  params.districtCode = formData.districtArr?.length ? formData.districtArr[formData.districtArr.length - 1] : ''
  saveInstitutionalData(params).then((res) => {
    InitInstitutionalData()
    res.data.msg && ElMessage.success(res.data.msg)
  })
}
// 保存按钮
const onConfirm = () => {
  validateFlag.value = !validateFlag.value
}

onActivated(() => {
  // 机构等级
  orgLevelData.value.length = 0
  common.getDicData('org_level').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      orgLevelData.value.push(item)
    })
  })
  InitInstitutionalData()
})
</script>

<template>
  <div class="institutional-data">
    <d-from
      label-position="right"
      :label-width="120"
      :reset-fields-flag="resetFieldsFlag"
      :validate-flag="validateFlag"
      :rules="rules"
      :form-data="formData"
      :form-items="fromItems"
      :form-line-num="1"
      @submit="onSubmit"
    >
      <template #districtArr>
        <el-cascader v-model="formData.districtArr" clearable placeholder="请选择省/市/区" :props="cascaderProps" style="width: 100%" />
      </template>
    </d-from>
    <el-button v-blur type="primary" class="from-submit-btn" :loading="loading" @click="onConfirm">
      保存
    </el-button>
  </div>
</template>

<style scoped lang="less">
.institutional-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 150px;
  form {
    width: 600px;
  }
  .from-submit-btn {
    margin-top: 20px;
    width: 160px;
    height: 32px;
  }
}
</style>
